package com.example.pong;

import android.graphics.Canvas;
import sheep.game.Layer;
import sheep.math.BoundingBox;

public class GameLayer extends Layer{
	
	/*
	 * Controller in the MVC. MVC are only implemented in the Score functionality
	 */
	
	private static final GameLayer gameLayer = new GameLayer();
	
	private Level level;
	private Ball ball;
	private Player player;
	private Computer computer;
	private DrawScore drawScore;
	private Score score;
	
	private GameLayer(){
		level = Level.getInstance();
		ball = Ball.getInstance();
		player = Player.getInstance();
		computer = Computer.getInstance();
		drawScore = DrawScore.getInstance();
		score = Score.getInstance();
		
		//Adding DrawScore as an observer of Score
		score.addObserver(drawScore);
		
		reset();
	}

	public static GameLayer getInstance(){
		return gameLayer;
	}
	
	@Override
	public void update(float dt) {
		ball.update(dt);
		player.update(dt);
		computer.update(dt);
		
		//Computer logic
		computer.update(ball.getPosition());
		
		//Racket logic
		if(player.collides(ball)) ball.setSpeed(ball.getSpeed().getX(), -ball.getSpeed().getY());
		if(computer.collides(ball)) ball.setSpeed(ball.getSpeed().getX(), -ball.getSpeed().getY());
		
		//Wall logic
		if(ball.getPosition().getX()<20||ball.getPosition().getX()>level.getWidth()-20){
			ball.setSpeed(-ball.getSpeed().getX(), ball.getSpeed().getY());
		}
		
		//Score logic
		if(ball.getPosition().getY()>=level.getHeight()){
			score.setComputerScore();
			reset();
		}
		if(ball.getPosition().getY()<=0) {
			score.setPlayerScore();
			reset();
		}
	}
	
	public String computeScoreString(){
		return "Player "+score.getPlayerScore()+" - "+score.getComputerScore()+" Computer";
	}

	@Override
	public void draw(Canvas canvas, BoundingBox box) {
		level.draw(canvas);
		ball.draw(canvas);
		player.draw(canvas);
		computer.draw(canvas);
		drawScore.draw(canvas, computeScoreString());
	}

	public void reset(){
		ball.setPosition(level.getWidth()/2, level.getHeight()/2);
		ball.setSpeed(-440, 150);
		player.setPosition(level.getWidth()/2, level.getHeight()-80);
		computer.setPosition(level.getWidth()/2, 40);
		player.stopPlayer();
	}

	public Player getPlayer() {
		return player;
	}
}
